package com.zxq.frame.rabbitmq.config;

import com.alibaba.fastjson.JSON;
import com.zxq.frame.core.ExchangeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.util.HexBin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
@Slf4j
public class RabbitPublishHelper {

    static RabbitPublishHelper rabbitPublishHelper = null;

    public static RabbitPublishHelper getInstance() {
        return rabbitPublishHelper;
    }

    @PostConstruct
    public void init(){
        rabbitPublishHelper = this;
    }


    @Autowired
    RabbitTemplate rabbitTemplate;

    @Value("${spring.rabbitmq.template.tcp-route-key}")
    String networkPublishKey;

    @Value("${spring.rabbitmq.template.http-route-key}")
    String webPublishKey;


    /**
     * 设备发送消息到MQ通道，整帧数据消息
     * @param exchangeDTO 数据帧消息
     */
    public void devPublishMqChannel(ExchangeDTO exchangeDTO){
        String jsonStr = JSON.toJSONString(exchangeDTO);
        rabbitTemplate.convertAndSend(exchangeDTO.getDeviceToMqRouteKey(),jsonStr.getBytes());
    }



    /**
     *  mq发送消息道设备，数据帧消息
     * @param exchangeDTO 交换数据
     */
    public void mqPublishFrameToNetworkChannel(ExchangeDTO exchangeDTO){
        String jsonStr = JSON.toJSONString(exchangeDTO);
        String message = String.format("publish to network key:%s value:%s",networkPublishKey,jsonStr);
        log.info(message);
        rabbitTemplate.convertAndSend(networkPublishKey,jsonStr.getBytes());
    }


    /**
     *  mq发送消息到平台，数据帧内的数据信息
     * @param rstDTO 交换数据
     */
    public void mqPublishFrameToWebChannel(ExchangeDTO rstDTO){
        String rstMessage = JSON.toJSONString(rstDTO);
        String message = String.format("key:%s cmdHex:%s value:%s",webPublishKey,rstDTO.getCmdHex(), HexBin.bytesToString(rstDTO.getData()));
        log.info("push to web:" + message);
        rabbitTemplate.convertAndSend(webPublishKey,rstMessage.getBytes());
    }





}
